from flask import request, jsonify, send_from_directory, make_response
import os
from app_factory import model
import logging

logger = logging.getLogger(__name__)

def register_routes(app):
    # 网站主页
    @app.route('/home')
    def home():
        home = make_response(send_from_directory(
            os.path.join(os.path.dirname(__file__), 'templates'),
            'home5.html'
        ))
        return home

    # 蒙古语情绪分析网页  http://127.0.0.1:5000/emotion-vector
    @app.route('/emotion-vector')
    def emotion_vector():
        response = make_response(send_from_directory(
            os.path.join(os.path.dirname(__file__), 'templates'),
            'index.html'
        ))
        # 自定义Response Headers X-Custom-Header: Value
        response.headers['X-Custom-Header'] = 'Value'
        return response

    @app.route('/check_word', methods=['GET', 'POST'])
    def check_word():
        """
        检查词汇是否存在于 Word2Vec 模型中
        GET 请求示例: /check_word?word=ᠶᠢᠨ
        POST 请求示例: {"word": "ᠶᠢᠨ"}
        """
        try:
            # 获取输入的词汇
            if request.method == 'GET':
                # .get(key, default) key存在返回key对应值，不存在返回default
                # .strip() 去掉字符串空格、换行符、制表符等
                word = request.args.get('word', '').strip()
            else:
                data = request.get_json()
                word = data.get('word', '').strip()

            if not word:
                return jsonify({"error": "请输入要查询的词汇"}), 400

            # 检查词汇是否在模型中
            if word in model.wv:
                vector = model.wv[word].tolist()  # 将 numpy 数组转换为 list
                response = {
                    "word": word,
                    "in_vocabulary": True,
                    "vector": vector,
                    "vector_dim": len(vector)
                }
                logger.info(f"找到词汇: {word}")
                # logger.info(f"向量: {vector}")
            else:
                response = {
                    "word": word,
                    "in_vocabulary": False,
                    "message": f"词汇 '{word}' 不在模型中"
                }
                logger.info(f"未找到词汇: {word}")

            return jsonify(response)

        except Exception as e:
            logger.error(f"处理请求时出错: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route('/api/get_vector', methods=['GET'])
    def get_vector():
        word = request.args.get('word')
        model_name = request.args.get('model')

        if not word:
            return jsonify({'error': '缺少word参数'}), 400

        try:
            if word in model.wv:
                vector = model.wv[word].tolist()
                return jsonify({
                    'vector': vector,
                    'dimension': len(vector),
                    'word': word,
                    'model': model_name
                })
            else:
                return jsonify({'error': f'单词"{word}"不在词汇表中'}), 404
        except Exception as e:
            return jsonify({'error': str(e)}), 500